package cn.ffcs.base.web;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import cn.ffcs.base.model.BaseEntity;
import cn.ffcs.base.service.IBaseService;

/**
 * 页面逻辑控制层基础代码<br/>
 * <table>
 * <tr>
 * <td>负责人/principal:</td>
 * <td colspan="2">liuzhh</td>
 * <tr>
 * <td>修改记录/revision:</td>
 * <td colspan="2"></td>
 * </tr>
 * <tr>
 * <td>日期:</td>
 * <td>修改人:</td>
 * <td>修改说明:</td>
 * </tr>
 * <tr>
 * <td></td>
 * <td></td>
 * <td></td>
 * </tr>
 * </table>
 * @author liuzhh
 * @version $Id$
 */
public class BaseAction<B extends BaseEntity> extends ActionSupport
{

    /** 网络标识 */
    private static final long serialVersionUID = -2538677449984501262L;
    /** 业务逻辑层 */
    protected IBaseService<B> baseService;
    /** 设置业务实体 */
    protected B baseEntity;
    /** 设置分页 */
    protected PageControl pageControl;
    /** 实体查询结果集 **/
    private List<B> results;
    /** 查询条件 **/
    private HashMap<String, Object> conds;
    /** 返回信息，用于操作成功提示**/
    protected String returnMsg;
    /** 返回url,用于操作成功跳转**/
    protected String returnUrl;
    /** 模糊查询条件 **/
    private HashMap<String, Object> likeFilter;
    /** 精确查询条件 **/
    private HashMap<String, Object> equalFilter;

    /**
     * 新增或修改字典类型数据
     * @return
     */
    public String saveOrUpdate()
    {
        baseService.saveOrUpdate(baseEntity);
        return SUCCESS;
    }

    /**
     * 获取页面对象
     * @param param
     * @return
     */
    protected String[] getContextObjects(String param)
    {
        ActionContext ctx = ActionContext.getContext();
        HttpServletRequest request = (HttpServletRequest) ctx
                .get(ServletActionContext.HTTP_REQUEST);

        String[] result = request.getParameterValues(param);
        if (result==null) result=new String[0];
        return result;
    }
    
    /**
     * 获取页面对象
     * @param param
     * @return
     */
    protected String getContextObject(String param)
    {
        ActionContext ctx = ActionContext.getContext();
        HttpServletRequest request = (HttpServletRequest) ctx
                .get(ServletActionContext.HTTP_REQUEST);

        String result = request.getParameter(param);
        return result;
    }
    
    /**
     * 获取页面对象
     * @param param
     * @return
     */
    protected Object getAppContextObject(String param)
    {
        ActionContext ctx = ActionContext.getContext();
        HttpServletRequest request = (HttpServletRequest) ctx
                .get(ServletActionContext.HTTP_REQUEST);

        Object result = request.getSession().getAttribute(param);
        return result;
    }  
    /**
     * 设置页面对象
     * @param param
     * @return
     */
    protected void setContextObject(String param,Object obj)
    {
        ActionContext ctx = ActionContext.getContext();
        HttpServletRequest request = (HttpServletRequest) ctx
                .get(ServletActionContext.HTTP_REQUEST);

        request.getSession().setAttribute(param, obj);

    }
    
    /**
     * 释放对象
     * @param param
     */
    protected void removeContextObject(String param)
    {
        ActionContext ctx = ActionContext.getContext();
        HttpServletRequest request = (HttpServletRequest) ctx
                .get(ServletActionContext.HTTP_REQUEST);

        request.getSession().removeAttribute(param);

    }
    
    /**
     * 获取所有实体数据
     * @return
     */
    public String findAll()
    {
        results = baseService.findAll();
        return SUCCESS;
    }
    
    /**
     * 获取关键字获取实体
     * @return
     */  
    public String findById()
    {
        if (baseEntity != null && baseEntity.getId() != 0)
        {
            baseEntity = (B) baseService.findById(baseEntity.getId());
        }
        return SUCCESS;
    }
    
    /**
     * 
     * 初始化业务数据
     * @return
     */
    public String init(){
        baseService.init();
        return SUCCESS;  
    }
    
    /**
     * 获取所有同类实体数据并实现翻页
     * @param currPage
     * @param pageSize
     * @return
     */
    public String findAllByPage()
    {

        if (pageControl == null)
        {
            pageControl = new PageControl();
        }

        pageControl = baseService.findAllByPage(pageControl.getPageNo(),
                pageControl.getPageSize());

        return SUCCESS;
    }
    
    /**
     * 
     * 组合查询条件
     * @return
     */
    @SuppressWarnings("unchecked")
	protected Criterion combineCond(){
        Criterion cond = null;
        if (conds != null)
        {
            //遍历参数表
            Iterator i = conds.entrySet().iterator();
            while (i.hasNext())
            {
                Entry entry = (Entry)i.next();
                String key=(String)entry.getKey();
                if (conds.get(key) != null
                        && !StringUtils.isEmpty(conds.get(key).toString()))
                {
                    if (cond == null)
                    {
	                    if(key.indexOf("name")!=-1){
	                		cond = Restrictions.like(key,"%"+conds.get(key)+"%");
	                	}else {
	                		cond = Restrictions.eq(key, conds.get(key));
	                	}
                    }
                    else
                    {	
                    	if(key.indexOf("name")!=-1){
                    		cond = Restrictions.and(cond,  Restrictions.like(key,"%"+conds.get(key)+"%"));
                    	}else {
                    		cond = Restrictions.and(cond,  Restrictions.eq(key,conds.get(key)));
                    	}
                    }
                }
            }
        }
        return cond;
    }
    
    /**
     * 获取分页数据
     * @return
     */
    @SuppressWarnings("unchecked")
    public String findByPage()
    {
              
        //如果第一次装置，默认参数
        if (pageControl == null)
        {
            pageControl = new PageControl();
        }
        
        pageControl = baseService.findByPage(combineCond(), pageControl.getPageNo(),
                pageControl.getPageSize());
        return SUCCESS;
    }
    
    /**
     * 
     * 通过页面参数获取条件数据
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<B> findBy()
    {
        Criterion cond = null;
        if (conds != null)
        {
            //遍历参数表
            Iterator i = conds.entrySet().iterator();
            while (i.hasNext())
            {
                Entry entry = (Entry)i.next();
                String key=(String)entry.getKey();
                if (conds.get(key) != null
                        && !StringUtils.isEmpty(conds.get(key).toString()))
                {
                    if (cond == null)
                    {
                        cond = Restrictions.eq(key, conds.get(key));
                    }
                    else
                    {
                        cond = Restrictions.and(cond, Restrictions.eq(key,
                                conds.get(key)));
                    }
                }
            }
        }
        
        return baseService.findBy(cond);
    }
    
    /**
     * 
     * 按查询条件获取总数并按照排序字段进行排序
     * @return
     */
    public List<B> findByAndOrder(String orderParam,String strOrder)
    {
        Criterion cond = null;
        if (conds != null)
        {
            //遍历参数表
            Iterator i = conds.entrySet().iterator();
            while (i.hasNext())
            {
                Entry entry = (Entry)i.next();
                String key=(String)entry.getKey();
                if (conds.get(key) != null
                        && !StringUtils.isEmpty(conds.get(key).toString()))
                {
                    if (cond == null)
                    {
                        cond = Restrictions.eq(key, conds.get(key));
                    }
                    else
                    {
                        cond = Restrictions.and(cond, Restrictions.eq(key,
                                conds.get(key)));
                    }
                }
            }
        }
        
        return baseService.findByAndOrder(cond, orderParam, strOrder);
    }
    
    /**
     * 注入业务逻辑层
     * @param baseService
     */
    public void setBaseService(IBaseService<B> baseService)
    {
        this.baseService = baseService;
    }

    /**
     * 获取业务实体
     * @return
     */
    public B getBaseEntity()
    {
        return baseEntity;
    }

    /**
     * 设置业务实体
     * @param baseEntity
     */
    public void setBaseEntity(B baseEntity)
    {
        this.baseEntity = baseEntity;
    }

    /**
     * 获取分页
     * @param baseEntity
     */
    public PageControl getPageControl()
    {
        return pageControl;
    }

    /**
     * 设置分页
     * @param baseEntity
     */
    public void setPageControl(PageControl pageControl)
    {
        this.pageControl = pageControl;
    }

    /**
     * 获取实体查询结果集
     * @param baseEntity
     */
    public List<B> getResults()
    {
        return results;
    }

    /**
     * 设置实体查询结果集
     * @param baseEntity
     */
    public void setResults(List<B> results)
    {
        this.results = results;
    }

    /**
     * 获取查询条件
     * @param baseEntity
     */
    public HashMap<String, Object> getConds()
    {
        return conds;
    }

    /**
     * 设置查询条件
     * @param baseEntity
     */
    public void setConds(HashMap<String, Object> conds)
    {
        this.conds = conds;
    }

    /**
     * 获取返回信息
     * @param baseEntity
     */
    public String getReturnMsg()
    {
        return returnMsg;
    }

    /**
     * 设置返回信息
     * @param baseEntity
     */
    public void setReturnMsg(String returnMsg)
    {
        this.returnMsg = returnMsg;
    }

    /**
     * 获取返回url
     * @param baseEntity
     */
    public String getReturnUrl()
    {
        return returnUrl;
    }

    /**
     * 设置返回url
     * @param baseEntity
     */
    public void setReturnUrl(String returnUrl)
    {
        this.returnUrl = returnUrl;
    }

    /**
     * @return the likeFilter
     */
    public HashMap<String, Object> getLikeFilter()
    {
        return likeFilter;
    }

    /**
     * @param likeFilter the likeFilter to set
     */
    public void setLikeFilter(HashMap<String, Object> likeFilter)
    {
        this.likeFilter = likeFilter;
    }

    /**
     * @return the equalFilter
     */
    public HashMap<String, Object> getEqualFilter()
    {
        return equalFilter;
    }

    /**
     * @param equalFilter the equalFilter to set
     */
    public void setEqualFilter(HashMap<String, Object> equalFilter)
    {
        this.equalFilter = equalFilter;
    }

}
